package itsm.isperp.workflow.listener;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.module.entity.bpm.BpmNodeUser;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.bpm.BpmNodeUserService;
import itsm.isperp.module.utils.CandidaterUtils;
import itsm.isperp.workflow.utils.BpmConst;
import itsm.isperp.workflow.utils.BpmMessageUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.impl.bpmn.behavior.ParallelMultiInstanceBehavior;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.IdentityLinkEntity;
import org.activiti.engine.task.IdentityLink;
import org.apache.commons.lang3.StringUtils;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2013-7-6
 * 
 */
public class TaskSignCreateListener extends BaseTaskListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected boolean execute(DelegateTask delegatetask,
			DelegateExecution delegateExecution, String defId, String nodeId) {
		String businessKey = delegateExecution.getProcessBusinessKey();

		Object nextStepAssignee = delegatetask.getVariable("nextStepAssignee");
		Map<String, IUser> mapUsers = new HashMap<>();

		String processDefId = delegatetask.getProcessDefinitionId();
		String processId = delegatetask.getProcessInstanceId();
		String processDefKey = processDefId.split(":")[0];

		boolean o = false;
		if (delegateExecution instanceof ExecutionEntity) {
			o = ((ExecutionEntity) delegateExecution).getActivity()
					.getActivityBehavior() instanceof ParallelMultiInstanceBehavior;
		}

		if (nextStepAssignee == null
				|| StringUtils.isEmpty((String) nextStepAssignee)) {
			// /如果人员以及有了这里要判断不能重复添加～TODO
			BpmNodeUserService bpmNodeUserService = (BpmNodeUserService) ContextHolder
					.getSpringBean("bpmNodeUserService");

			List<BpmNodeUser> nodeUsers = bpmNodeUserService
					.findAllCandidaterByDefIdAndNodeId(defId, nodeId);

			if (o) {
				Map<String, IUser> mapUsers2 = new HashMap<>();

				for (BpmNodeUser user : nodeUsers) {
					CandidaterUtils.addToCandidaterInProcess(
							bpmNodeUserService, mapUsers2, user, businessKey,
							processDefKey, processId, nodeId, delegatetask);
				}
				Set<String> set = mapUsers2.keySet();

				List<String> users = new ArrayList<String>();
				for (String s : set) {
					users.add(s);
				}

				String newNextStepAssignee = "";
				for (int i = 1; i < users.size(); i++) {
					newNextStepAssignee += "," + users.get(i);
				}

				if (StringUtils.isNotEmpty(newNextStepAssignee)) {
					newNextStepAssignee = newNextStepAssignee.substring(1);
				}

				delegatetask.setVariable("nextStepAssignee",
						newNextStepAssignee);

				IUser u = mapUsers2.get(users.get(0));
				mapUsers.put(u.getUsername(), u);
				delegatetask.addCandidateUser(users.get(0));

			} else {

				for (BpmNodeUser user : nodeUsers) {
					CandidaterUtils.addToCandidaterInProcess(
							bpmNodeUserService, mapUsers, user, businessKey,
							processDefKey, processId, nodeId, delegatetask);
				}
				delegatetask.addCandidateUsers(mapUsers.keySet());
			}

		} else {

			AppUserService appUserService = ContextHolder
					.getSpringBean("appUserService");

			String username = nextStepAssignee.toString();

			if (o) {
				// 指定多用户
				if (username.contains(",")) {
					String[] users = username.split(",");

					String newNextStepAssignee = "";
					for (int i = 1; i < users.length; i++) {
						newNextStepAssignee += "," + users[i];
					}

					if (StringUtils.isNotEmpty(newNextStepAssignee)) {
						newNextStepAssignee = newNextStepAssignee.substring(1);
					}

					delegatetask.setVariable("nextStepAssignee",
							newNextStepAssignee);
					IUser u = appUserService.findByUsername(users[0]);
					mapUsers.put(u.getUsername(), u);
					delegatetask.addCandidateUser(users[0]);
				} else {
					mapUsers.put(username,
							appUserService.findByUsername(username));

					delegatetask.addCandidateUser(username);
				}

			} else {

				if (username.contains(",")) {
					String[] users = username.split(",");

					for (String s : users) {
						mapUsers.put(username, appUserService.findByUsername(s));
						delegatetask.addCandidateUser(s);
					}

				} else {
					mapUsers.put(username,
							appUserService.findByUsername(username));

					delegatetask.addCandidateUser(nextStepAssignee.toString());
				}
			}
		}
		// TODO
		// if (mapUsers.size() == 0) {
		// throw new RuntimeException("下一步没有处理人！");
		// }

		Set<IdentityLink> s = delegatetask.getCandidates();
		for (IdentityLink il : s) {
			IdentityLinkEntity ile = (IdentityLinkEntity) il;
			ile.setProcessDefId(processDefId);
			ile.setProcessInstanceId(processId);
		}

		// 通知
		BpmMessageUtils.sendMessages(delegatetask, processDefKey,
				delegatetask.getTaskDefinitionKey(), mapUsers, businessKey);

		return true;
	}

	@Override
	protected String getScriptType() {
		return BpmConst.StartScript;
	}

}
